package com.ruoyi.system.utils;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.Assert;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.ACustomeruser;
import com.ruoyi.system.mapper.ACustomeruserMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 48824
 */
public class LoginUtils {

    // redis缓存用户信息 使用spring进行管理
    private static RedisCache loginCache = SpringUtils.getBean(RedisCache.class);
    // 定义redis存储标识
    private static String loginKey = "loginKey";

    // 通过springBean 获得 mapper
    private static ACustomeruserMapper user = SpringUtils.getBean(ACustomeruserMapper.class);


    // 缓存过期时间（单位：秒）
    private static int expireTime = 1800; // 30分钟

    // 通过openId查询用户信息
    public static String loginByOpenId(String openId) {
        ACustomeruser aUser = user.selectOpenId(openId);
        return cacheUser(aUser, "openId不存在登录失败");
    }
    // 通过手机号查询用户信息
    public static String loginByPhone(String phone) {
        ACustomeruser aUser = user.selectPhoneNumber(phone);
        return cacheUser(aUser, "手机号不存在登录失败");
    }

    private static String cacheUser(ACustomeruser aUser, String errorMsg) {
        Assert.notEmpty(aUser,()-> new ServiceException(errorMsg, HttpStatus.UNAUTHORIZED));
        // 生成UUID
        UUID uuid = UUID.randomUUID();
        //使用hash存储数据
        loginCache.setCacheMapValue(loginKey, uuid.toString(), aUser.getUserId());
        // 设置过期时间
        loginCache.expire(loginKey,expireTime, TimeUnit.DAYS);
        return uuid.toString();
    }

    // 用户登录
    public static String login(String loginKey) {
        try {
            return loginByOpenId(loginKey);
        } catch (ServiceException e) {
            return loginByPhone(loginKey);
        }
    }

    // 获取用户信息
    public static ACustomeruser getUser(String uuid){
        Long id = loginCache.getCacheMapValue(loginKey, uuid);
        Assert.notEmpty(id,()->  new AccessDeniedException("用户信息不存在"));
        return LoginUtils.user.selectACustomeruserByUserId(id);
    }

    public static ACustomeruser getUser(){
        // 当前请求中获取Request对象
        HttpServletRequest holderRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 请求头
        String auth = holderRequest.getHeader("auth");
        Assert.notEmpty(auth,()->new AccessDeniedException("请求头参数为空"));
        return getUser(auth);
    }
}
